package xworker.swt.data.listeners;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Control;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.dataObject.DataObject;
import xworker.dataObject.DataObjectListener;

public class SwtDataObjectListener implements DataObjectListener {
    Thing thing;
    ActionContext actionContext;

    public SwtDataObjectListener(Thing thing, ActionContext actionContext){
        this.thing = thing;
        this.actionContext = actionContext;
    }

    @Override
    public void changed(DataObject dataObject) {
        thing.doAction("changed", actionContext, "dataObject", dataObject, "listener", this);
    }

    public static SwtDataObjectListener create(ActionContext actionContext){
        Thing self = actionContext.getObject("self");

        Control control = self.doAction("getControl", actionContext);
        if(control == null){
            if(actionContext.get("parent") instanceof Control){
                control = actionContext.getObject("parent");
            }
        }
        DataObject dataObject = self.doAction("getDataObject", actionContext);

        SwtDataObjectListener listener = new SwtDataObjectListener(self, actionContext);
        dataObject.addListener(listener);

        if(control != null && !control.isDisposed()){
            control.addListener(SWT.Dispose, event -> dataObject.removeListener(listener));
        }

        actionContext.g().put(self.getMetadata().getName(), listener);

        return listener;
    }
}
